package com.yydm.serviceacls.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yydm.serviceacls.entity.LoginUser;
import com.yydm.serviceacls.entity.Permission;
import com.yydm.serviceacls.entity.User;
import com.yydm.serviceacls.mapper.PermissionMapper;
import com.yydm.serviceacls.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;


/**
 * <p>
 * 自定义userDetailsService - 认证用户详情
 * </p>
 *
 * @author qy
 * @since 2019-11-08
 */
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userServer;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //1,查询用户信息
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        User user = userServer.getOne(queryWrapper);
        //如果没有查询到用户就抛出异常
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户名或者密码错误");
        }

        //  2,查询用户权限 先暂时把权限数据写死 test admin
        List<Permission> authoritieslist = permissionMapper.selectPermsByUserId(user.getId());
        System.out.println(authoritieslist);

        //3,封装成userdtails对象
        return new LoginUser(user, authoritieslist);
    }



}
